import { Vec2 } from 'cc';
import { Sprite } from 'cc';
import { _decorator, Component, Node } from 'cc';
import { eventManager } from '../../common/eventManager';
import { eliminateConsts } from './EliminateConst';
import { eliminateGameManager } from './EliminateGameManager';
const { ccclass, property } = _decorator;

const timesTimeMap = {
    2: 10,
    3: 9,
    4: 8,
    5: 7,
    6: 6,
    7: 5,
    8: 4,
    9: 3,
    10: 2,
    11: 1,
    12: 0.5,
    13: 0.1
}

@ccclass('EliminateProgress')
export class EliminateProgress extends Component {

    protected _startCountdown: boolean = false;

    public set startCountdown(v: boolean) {
        /** 从新开始计时 */
        this._totalDt = 0;
        if (v) {
            this._resetProgress();
            eliminateGameManager.game.times += 1;
            this._totalTime = timesTimeMap[eliminateGameManager.game.times] || 0.1;
        }
        this._startCountdown = v;
    }

    public get startCountdown() {
        return this._startCountdown;
    }

    protected _totalDt: number = 0;
    /** 默认15秒内才会有倍数逻辑 */
    protected _totalTime: number = 15;

    private bar: Sprite = null;

    protected __preload(): void {
        this.bar = this.node.getChildByName("progressBar").getComponent(Sprite);
    }

    protected onLoad(): void {
        // this.node.getComponentInChildren(MeshRenderer);
        this.bar.fillCenter = new Vec2(0.5, 0.5);
        this.bar.fillType = Sprite.FillType.RADIAL;
        this.bar.fillStart = 0.4;
        // this._resetProgress();
    }

    protected _resetProgress() {
        if (this.bar) {
            this.bar.fillRange = 0.7;
        }
    }

    /**
     * 更新进度条的进度 
     * @param  {number} progressValue 0 - 1 需要重新映射到-0.5 - 0的范围内
     */
    updateProgress(progressValue: number) {
        // 确保传入的进度在0-1范围内
        progressValue = Math.max(0, Math.min(1, progressValue));
        // 映射progressValue从0-1到0.7到0的范围
        // 0% 进度对应-0.5，100% 进度对应0
        const mappedValue = 0.7 - progressValue * 0.7;
        this.bar.fillRange = mappedValue;
    }

    update(deltaTime: number) {
        if (this.startCountdown && !eliminateGameManager.game.gameOver) {
            this._totalDt += deltaTime;
            if (this._totalDt >= this._totalTime) {
                this._totalDt = 0;
                /** 停止倒计时逻辑 */
                this.startCountdown = false;
                // 倒计时结束之后重置倍数为1
                eliminateGameManager.game.times = 1;
                // 连消倒计时结束
                eventManager.emit(eliminateConsts.messages.ELIMINATE);
            } else {
                // 更新进度值
                this.updateProgress(this._totalDt / this._totalTime);
            }
        }
    }
}

